import 'package:flutter/material.dart';

/// 平移组件
class TranslateWidget extends StatefulWidget {
  final Widget child;
  final Offset offset;
  final int duration;
  final Curve? curve;
  final bool transformHitTests;
  final FilterQuality? filterQuality;
  final bool animate;

  //循环播放
  final bool repeat;

  // 反向
  final bool reverse;

  const TranslateWidget({
    super.key,
    required this.child,
    this.offset = Offset.zero,
    this.duration = 300,
    this.curve,
    this.transformHitTests = true,
    this.filterQuality,
    this.animate = false,
    this.repeat = false,
    this.reverse = false,
  });

  @override
  _TranslateWidgetState createState() => _TranslateWidgetState();
}

class _TranslateWidgetState extends State<TranslateWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Offset> _animation;
  late Offset _previousOffset;

  @override
  void initState() {
    super.initState();
    _previousOffset = widget.offset;
    _controller = AnimationController(
      duration: Duration(milliseconds: widget.duration),
      vsync: this,
    );

    _animation = Tween<Offset>(begin: _previousOffset, end: widget.offset).animate(
      widget.curve == null ? _controller : CurvedAnimation(parent: _controller, curve: widget.curve!),
    );

    _start();
  }

  // 当动画可用时启动动画
  void _start() {
    if (widget.animate) {
      if (widget.repeat) {
        _controller.repeat(reverse: widget.reverse);
      } else {
        _controller.forward();
      }
    }
  }

  @override
  void didUpdateWidget(TranslateWidget oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 当偏移量、持续时间或动画曲线发生变化时重置动画
    if (widget.animate && (widget.offset != oldWidget.offset || widget.duration != oldWidget.duration || widget.curve != oldWidget.curve)) {
      _previousOffset = _animation.value;
      _controller
        ..duration = Duration(milliseconds: widget.duration)
        ..reset();
      _start();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.animate) {
      // 动画模式下使用AnimatedBuilder构建平移动画
      return AnimatedBuilder(
        animation: _controller,
        builder: (context, child) {
          return Transform.translate(
            offset: _animation.value,
            transformHitTests: widget.transformHitTests,
            filterQuality: widget.filterQuality,
            child: child,
          );
        },
        child: widget.child,
      );
    } else {
      // 非动画模式下直接应用平移变换
      return Transform.translate(
        offset: widget.offset,
        transformHitTests: widget.transformHitTests,
        filterQuality: widget.filterQuality,
        child: widget.child,
      );
    }
  }
}
